package com.sjh.net

import java.util.concurrent.TimeUnit

import io.reactivex.Observable
import io.reactivex.functions.Function
import java.io.IOException

/**
 * @author Extends
 * @date 2020/8/27
 */
class RetryWithDelay(private val maxRetries: Int, private val retryDelayMillis: Int = 200) :
    Function<Observable<out Throwable>, Observable<*>> {
    private var retryCount: Int = 0

    override fun apply(attempts: Observable<out Throwable>): Observable<*> {
        return attempts
            .flatMap { throwable ->
                if (throwable is IOException && ++retryCount <= maxRetries) {
                    Observable.timer(retryDelayMillis.toLong(), TimeUnit.MILLISECONDS)
                } else Observable.error<Any>(throwable)
            }
    }

}

